package com.siblings.loan.ui.permission

import android.Manifest
import android.view.View
import androidx.fragment.app.Fragment
import androidx.fragment.app.FragmentManager
import androidx.fragment.app.FragmentStatePagerAdapter
import androidx.viewpager.widget.ViewPager
import com.lib.base.base.BaseActivity
import com.lib.base.base.BaseFragment
import com.siblings.loan.R
import com.siblings.loan.app.Apps
import com.siblings.loan.databinding.ActPermissionBinding
import com.siblings.loan.databinding.ItemPageIndicatorBinding
import com.siblings.loan.http.HttpHelper
import com.siblings.loan.ui.permission.impl.SibPermissionPresenterImpl
import com.siblings.loan.ui.permission.view.ISibPermissionView
import com.siblings.loan.ui.user.act.SibLoginAct
import com.siblings.loan.utils.PermissionUtils
import com.siblings.loan.utils.event.SibEventType
import com.siblings.mvp.MvpAct
import org.json.JSONObject

/**
 * SiblingsLoan
 * @Author wwdeng
 * @CreateTime: 2024/7/5 13:41
 * @Annotation：权限申请
 */
class SibPermissionAct: MvpAct<ISibPermissionView, SibPermissionPresenterImpl>(),ISibPermissionView {

    lateinit var binding: ActPermissionBinding

    var pageList: ArrayList<BaseFragment>? = null
    override fun getSibRootView(): View {
        binding = ActPermissionBinding.inflate(layoutInflater)
        return binding.root
    }

    override fun initSibView() {
        pageList = arrayListOf()
    }

    override fun initSibListener() {
        binding.viewPager.addOnPageChangeListener(object : ViewPager.OnPageChangeListener{
            override fun onPageScrolled(position: Int, positionOffset: Float, positionOffsetPixels: Int, ) {
            }
            override fun onPageSelected(position: Int) {
                mvpPresenter.onSibCheckPageClick(position)
            }
            override fun onPageScrollStateChanged(state: Int) {
            }
        })

        //拒绝
        binding.btnDeny.setOnClickListener {
            mvpPresenter.onSibDenyClick()
        }

        //同意权限
        binding.btnAgree.setOnClickListener {
            mvpPresenter.onSibAgreeClick()
        }

        //已授权
        binding.authorizedLayout.setOnClickListener{
        }

        //被禁止
        binding.bannedLayout.setOnClickListener {
            mvpPresenter.onSibBannedClick()
        }
    }

    override fun initSibData() {
        mvpPresenter.loadSibPermissionListAction()
    }

    override fun createMvpPresenter(): SibPermissionPresenterImpl {
        return SibPermissionPresenterImpl(this)
    }

    /* 权限请求监听 */
    override fun onRequestPermissionsResult(requestCode: Int, permissions: Array<out String>, grantResults: IntArray) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults)
        PermissionUtils.onRequestPermissionsResult(this,requestCode, permissions,grantResults)
    }

    override fun onResume() {
        super.onResume()
        mvpPresenter.onSibPermissionResume()
    }

    override fun getSibActivity(): BaseActivity {
        return this
    }

    /**
     * 未申请
     */
    override fun showSibPermissionNotObtained(){
        binding.defaultLayout.visibility = View.VISIBLE
        binding.authorizedLayout.visibility = View.GONE
        binding.bannedLayout.visibility = View.GONE
    }

    /**
     * 已允许
     */
    override fun showSibPermissionAuthorized(){
        binding.defaultLayout.visibility = View.GONE
        binding.authorizedLayout.visibility = View.VISIBLE
        binding.bannedLayout.visibility = View.GONE
    }

    /**
     * 已拒绝
     */
    override fun showSibPermissionBanned(){
        binding.defaultLayout.visibility = View.GONE
        binding.authorizedLayout.visibility = View.GONE
        binding.bannedLayout.visibility = View.VISIBLE
    }

    /**
     * 进入登录页面
     */
    override fun showSibLoginPage() {
        onIntent(SibLoginAct::class.java)
        finish()
    }

    /**
     * 设置显示权限
     */
    override fun showSibPermissionPage(index: Int) {
        binding.viewPager.setCurrentItem(index)
        addIndicatorViews(index)

        val item = mvpPresenter.getSibPermissionList()[index]
        binding.imgView.setImageResource(item.optInt("icon"))
        binding.textTitle.text = item.optString("title")
        binding.textTitle.setTextColor(item.optInt("titleColor"))
    }

    /**
     * 设置权限列表
     */
    override fun showSibPermissionList(pList: ArrayList<JSONObject>) {
        pList.forEach {
            pageList!!.add(SibPermissionPage(it))
        }
        val pageAdapter = MyFragmentPagerAdapter(pageList!!,supportFragmentManager)
        binding.viewPager.adapter = pageAdapter
    }


    /**
     * 添加指示器
     */
    private fun addIndicatorViews(index: Int){
        val item = mvpPresenter.getSibPermissionList()[index]
        binding.indicatorLayout.removeAllViews()
        for (i in 0..<pageList!!.size){
            val indicatorBinding = ItemPageIndicatorBinding.inflate(layoutInflater)
            when (i){
                index -> {
                    when(item.optString("permission")){
                        Manifest.permission.READ_PHONE_STATE -> {
                            indicatorBinding.imgView.setImageResource(R.drawable.sib_indicator_phone_state)
                        }
                        Apps.context.getString(R.string.permission_app_list_title) -> {
                            indicatorBinding.imgView.setImageResource(R.drawable.sib_indicator_app_list)
                        }
                        else -> {
                            indicatorBinding.imgView.setImageResource(R.drawable.sib_indicator_select)
                        }
                    }
                }
                else -> {
                    indicatorBinding.imgView.setImageResource(R.drawable.sib_indicator_normal)
                }
            }
            binding.indicatorLayout.addView(indicatorBinding.root)
        }
    }

    private class MyFragmentPagerAdapter(val pageList: ArrayList<BaseFragment>,fm: FragmentManager) : FragmentStatePagerAdapter(fm,BEHAVIOR_RESUME_ONLY_CURRENT_FRAGMENT) {
        override fun getItem(position: Int): Fragment {
            return pageList[position]
        }
        override fun getCount(): Int {
            return pageList.size
        }
    }

    override fun onStart() {
        super.onStart()
        HttpHelper.addSibEventAction(SibEventType.PAGE.SIB_PAGE_PERMISSION_START,"")
    }

    override fun onDestroy() {
        super.onDestroy()
        HttpHelper.addSibEventAction(SibEventType.PAGE.SIB_PAGE_PERMISSION_END,"")
    }
}